#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gui import *
from gameinit import *
from player import *
        

class Minimap(Widget):
    REFRESH_ON_MOUSE_OVER = False
    REFRESH_ON_MOUSE_DOWN = True
    REFRESH_ON_MOUSE_CLICK = True
    REFRESH_ON_MOUSE_LEAVE = False
    
    # The boardmap is a board Object
    def __init__(self, boardmap , position = (0,600),size=(210,210),winHexSize=(10,8), parent = None, style = None, enabled = True):
        self.board = boardmap
        self.boardsize = (self.board.width,self.board.height)
        self.winHexSize = winHexSize
        # Size of the minimap in pixels :
        self.minimapWidth ,self.minimapHeight = size 
         

        miniTileWidthTmp = self.minimapWidth / self.board.width
        miniTileHeightTmp = self.minimapHeight / (self.board.height + 0.5)
        
        miniTileSize = min(miniTileWidthTmp / 1.5,miniTileHeightTmp / (2*COS60))

        # Now we generate the tiles which will be used for the minimap :
        global minimapTiles
        scale = float(miniTileSize)/35.0
        minimapTiles.setTileScaling(scale)
        
        for h in self.board.hexs:
            h.refreshSkin()
        
        miniTileWidth = miniTileSize * 1.5
        miniTileHeight = miniTileSize *2*COS60
        

        # Resize of the minimap to take into account the computed size of the minimap tiles
        self.minimapWidth = miniTileWidth * self.board.width
        self.minimapHeight = miniTileHeight * (self.board.height + 0.5)
        
        # Size of the displayed portion of the map in hex
        W,H = winHexSize
        self.windowHexWidth = min (W ,self.board.width)
        self.windowHexHeight = min(H ,self.board.height)
        
        # Size of the window which allows to select the portion of the map to see (in pixels)
        self.windowWidth = self.windowHexWidth * minimapTiles.width
        self.windowHeight = (self.windowHexHeight+0.5) * minimapTiles.height
        x,y = position
        self.windowRect = pygame.Rect(x,y,self.windowWidth,self.windowHeight)

        # Hex Coordinates for the window:
        self.xWindowHex,self.yWindowHex = 0,0
        self.usedsize = (self.minimapWidth,self.minimapHeight)


        # Set the minimap texture:
        self.img = pygame.Surface(self.usedsize)
        for hx in self.board.hexs :
            x,y = hx.coord
            hx.tile.drawOnSurface(self.img,x,y,0,0,0,0,hx.pos,scale)
        
        self.image = pygl2d.image.Image(self.img)
        
        Widget.__init__(self,position,size,parent,style,enabled)
        self.updateWindow()
        
        print "Mini tile size", miniTileWidth,miniTileHeight, miniTileSize
        print "Minimap size : ", size , self.usedsize
        #self.visible = False

        

    def refreshBoard(self):
        print "REFRESH MINIMAP ,",self.boardsize,self.board.width,self.board.height
        
        self.refreshBoardSub()

        
    
    def refreshBoardSub(self):
        
        miniTileWidthTmp = self.size[0] / self.board.width
        miniTileHeightTmp = self.size[1] / (self.board.height+0.5)
        
        miniTileSize = min(miniTileWidthTmp / 1.5,miniTileHeightTmp / (2*COS60))
        #TODO CLEAN THIS PART OF THE CODE 
        # Now we generate the tiles which will be used for the minimap :
        global minimapTiles
        scale = float(miniTileSize)/35.0
        minimapTiles.setTileScaling(scale)  #TileCollection(HEXIMGPATH,35,(),BOARD) # float(miniTileSize)/35.0 <=> Resize
    
        for h in self.board.hexs:
            h.refreshSkin()

        if self.boardsize != (self.board.width,self.board.height):
            self.boardsize = (self.board.width,self.board.height)
            miniTileWidth = miniTileSize * 1.5
            miniTileHeight = miniTileSize *2*COS60
            
            print "RESIZE"
            # Resize of the minimap to take into account the computed size of the minimap tiles
            self.minimapWidth = miniTileWidth * self.board.width
            self.minimapHeight = miniTileHeight * (self.board.height + 0.5)
            
            # Size of the displayed portion of the map in hex
            W,H = self.winHexSize
            self.windowHexWidth = min (W ,self.board.width)
            self.windowHexHeight = min(H ,self.board.height)
            
            # Size of the window which allows to select the portion of the map to see (in pixels)
            self.windowWidth = self.windowHexWidth * minimapTiles.width
            self.windowHeight = (self.windowHexHeight+0.5) * minimapTiles.height
            x,y = self.position
            self.windowRect = pygame.Rect(x,y,self.windowWidth,self.windowHeight)

            # Hex Coordinates for the window:
            self.xWindowHex,self.yWindowHex = 0,0
            self.usedsize = (self.minimapWidth,self.minimapHeight)

        self.img = pygame.Surface(self.usedsize)
        
        for hx in self.board.hexs :
            x,y = hx.coord
            hx.tile.drawOnSurface(self.img,x,y,0,0,0,0,hx.pos,scale)
        
        self.image = pygl2d.image.Image(self.img)
        
        self.updateWindow()
        
    def updateWindow(self):
        x,y = self.windowRect.topleft
        x0,y0 = self.rect.topleft
        self.xWindowHex,self.yWindowHex = int((x-x0)/minimapTiles.width) , int((y-y0)/minimapTiles.height)
        print self.getWindowHex()
        
    def getWindowHex(self):
        return (self.xWindowHex,self.yWindowHex,self.xWindowHex+self.windowHexWidth-1,self.yWindowHex+self.windowHexHeight-1)
    
    def draw(self,surf):
        if self.visible:
            
            if self.board.isModified():
                self.refreshBoardSub()

            color = [0,255,0]
            pygl2d.draw.rect(self.rect, color, width=2)
            self.drawMinimap() 
            
            self.drawWindow()
        

    def drawMinimap(self):
        # TODO : Coller toutes les tiles sur une seule texture et afficher cette texture.
        self.image.draw(self.position)
        #for hx in self.board.hexs :
        #    hx.drawOnMinimap(self.position)
        
    def drawWindow(self):
        color = [255,255,255]
        pygl2d.draw.rect(self.windowRect, color, width=1)
        #print "DRAW window : ",self.windowRect




    
    
class WindowMap(Widget):
    REFRESH_ON_MOUSE_OVER = True
    REFRESH_ON_MOUSE_DOWN = True
    REFRESH_ON_MOUSE_CLICK = True
    REFRESH_ON_MOUSE_LEAVE = False
    
    def __init__(self, boardmap , position = (0,0),size=(800,600), parent = None, style = None, enabled = True):
        self.board = boardmap
        wp,hp = size
        self.width = wp
        self.height = hp
        self.hexWidth = int(wp/(mapTiles.width))
        self.hexHeight = int((hp)/(mapTiles.height)) - 1
        
        # Coordinates in hexs of the upperleft corner
        self.hexX = 0
        self.hexY = 0

        # Resize of the WindowMap in pixels :
        self.width = (self.hexWidth+0.5) * mapTiles.width
        self.height = (self.hexHeight + 0.5) * mapTiles.height
        size = (self.width,self.height)
        Widget.__init__(self,position,size,parent,style,enabled)

        #exceedH = self.width - self.hexWidth * mapTiles.width
        #exceedV = self.height - (self.hexHeight + 0.5) * mapTiles.height
        
        borderTile = pygame.image.load("data/img/gui/border1.png")
        borderSurf = pygame.Surface((self.width,borderTile.get_height()))
        drawHTiled((0,0),self.width,borderTile,borderSurf)
        self.borderBottom = pygl2d.image.Image(borderSurf)
        
        borderTile = pygame.image.load("data/img/gui/border2.png")
        borderSurf = pygame.Surface((borderTile.get_width(),self.height))
        drawVTiled((0,0),self.height,borderTile,borderSurf)
        self.borderLeft = pygl2d.image.Image(borderSurf)
        #self.visible = False
        self.backgroundSurf = pygame.Surface((self.width,self.height))
        self.backgroundSurf.blit(self.board.background,(0,0))
        w,h = self.board.background.get_rect().size
        self.backgroundSurf.blit(pygame.transform.flip(self.board.background,False,True),(0,h))
        self.backgroundSurf.blit(pygame.transform.flip(self.board.background,True,False),(w,0))
        self.backgroundSurf.blit(pygame.transform.flip(self.board.background,True,True),(w,h))
        self.backgrounImage = pygl2d.image.Image(self.backgroundSurf)
                                        

    def updateCoords(self,x,y):
        self.hexX = x
        self.hexY = y

    def getHexCoords(self):
        return self.hexX, self.hexY

    def getWindowHexSize(self):
        return (self.hexWidth,self.hexHeight)

    def draw(self,surf):
        if self.visible:
            self.backgrounImage.draw(self.position)#self.board.background.draw(self.position)
            self.board.drawSubPart(self.hexX,self.hexY,self.hexX+self.hexWidth-1,self.hexY+self.hexHeight-1)
            self.borderBottom.draw((self.position[0],self.position[1]+self.height))

            self.borderLeft.draw((self.position[0]+self.width - mapTiles.width / 6,self.position[1]))


def Pix2Hex(coord,side,topleftHexCoord=(0,0)):
    hstep = 2*side*COS60
    xpix,ypix = coord
    xHex0,yHex0 = topleftHexCoord()
    # Pix2Hex coordinates
    a = int( xpix / (side * 1.5)) 
    
    xpixHex = xpix - a * 1.5 * side

    isEvenColumn = ((xHex0 + a) % 2 == 0)
    
    if isEvenColumn:
        b = int( ypix / hstep) 
        ypixHex = ypix - b * hstep
    else:
        b = int( ypix  / hstep -0.5)
        ypixHex = ypix - (b+0.5)  * hstep

    print xpixHex,ypixHex
    xHex, yHex = 0,0
    
    if xpixHex >= side/2:
        xHex = a
        yHex = b

    else:
        if ypixHex < hstep / 2 - 2*COS60 * xpixHex :
            xHex = a - 1
            if isEvenColumn:
                yHex = b - 1
                
            else:
                yHex = b 
                
        elif ypixHex > hstep / 2 + 2*COS60 * xpixHex :
            xHex = a - 1
            if isEvenColumn:
                yHex = b 
                
            else:
                yHex = b + 1 
                
        else :
            xHex = a
            yHex = b
    xHex+=xHex0
    yHex+=yHex0
    if xHex < 0 :
        xHex = None
    if yHex < 0 :
        yHex = None

    return xHex,yHex

class HexDetails(Widget,Container):
    REFRESH_ON_MOUSE_OVER = False
    REFRESH_ON_MOUSE_DOWN = False
    REFRESH_ON_MOUSE_CLICK = True
    REFRESH_ON_MOUSE_LEAVE = False
    
    def __init__(self ,player,position=(0,0),size=(100,100) ,parent = None, style = None, enabled = True):
    
        # Size in pixels :
        self.width,self.height = size
        
        self.player = player
        size = (self.width,self.height)
        pw,ph = parent.size
    
        Widget.__init__(self,position,size,parent,style,enabled)
        Container.__init__(self)
        self.posHex = (self.position[0]+self.width/2 - mapTiles.width/2,self.position[1]+self.height/2 - mapTiles.height/2)

    def draw(self,surf):
        if self.visible:
            color = [0,255,0]
            pygl2d.draw.rect(self.rect, color, width=2)
            if len(self.player.selectedHexs) >0 :
                hexa = self.player.selectedHexs[0]
                if hexa.skin!=None:
                    hexa.tile.draw(0,0,0,0,self.posHex[0],self.posHex[1],hexa.pos)


# Callbacks :
# For minimap :
def miniMapOnClick(minimap):
    x0,y0 = minimap.position
    xr,yb = minimap.usedsize #minimap.rect.bottomright
    xr += x0
    yb += y0
    print x0,y0,xr,yb
    windowRect = minimap.windowRect
    xm,ym = pygame.mouse.get_pos()
    x1,y1 = xm - x0 ,ym -y0
    x2,y2 = xr - xm,yb - ym
    

    newX,newY = 0,0
    
    if x1 < windowRect.width/2:
        newX = x0 + windowRect.width/2
    elif x2< windowRect.width/2:
        newX = xr - windowRect.width/2
    else :
        newX = xm 

    if y1 < windowRect.height/2:
        newY = y0 + windowRect.height/2
    elif y2< windowRect.height/2:
        newY = yb - windowRect.height/2
    else :
        newY = ym 
    print newX,newY
    windowRect.center = newX,newY
    minimap.updateWindow()

# For the window map display
def WindowMapOnClick(windowMap):
    x0,y0 = windowMap.position
    topleftHexCoord = windowMap.getHexCoords
    xm,ym = pygame.mouse.get_pos()
    side = mapTiles.side
    coord = (xm-x0,ym-y0)
    x,y = Pix2Hex(coord,side,topleftHexCoord)
    h = windowMap.board.getHex(x,y)
    player = windowMap.board.currentPlayer
    player.unselect()
    player.select(h)


# For the detail hex display
        
if __name__ == "__main__":
    import pygl2d
    import gui
    from board import *
    

    #winWidth = 12
    #winHeight = 8

    # Init GUI
    desktop = gui.Desktop()
    
    
    player = Player("player1") 
    players = [player]
    
    ship = board("data/shipmaps/shiptest2.txt",players)
    ship.setCurrentPlayer(player)

    windowMap=WindowMap(ship,position = (0,0),size=(800,SCREEN_HEIGHT), parent = desktop)
    winHexSize=windowMap.getWindowHexSize()
    minimapship = Minimap(ship,position = (SCREEN_WIDTH-210,100),size=(210,210),winHexSize=winHexSize, parent = desktop)
    hexDetails = HexDetails(player,position=(SCREEN_WIDTH-210,0),size=(210,100),parent = desktop)
    minimapship.onClick = miniMapOnClick
    windowMap.onClick = WindowMapOnClick
    
    print pygame.display.get_surface().get_size()
    print windowMap.getWindowHexSize()
    
    clock = pygame.time.Clock()
    running = 1
    pygame.display.flip()

    while running:
        clock.tick(30.0)

        for e in gui.setEvents():
            pass

        desktop.update()

        x0,y0,x1,y1 = minimapship.getWindowHex()

        windowMap.updateCoords(x0,y0)

        pygl2d.window.begin_draw()
        
        
        desktop.draw()
        
        pygl2d.window.end_draw()
        pygame.display.flip()
        display.set_caption(str(int(clock.get_fps())))
        for e in pygame.event.get():
            if e.type == QUIT:
                running = 0
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    running = 0
        

    pygame.quit()
    

    
